package com.xunshangwang.pinhaohuo.ui.fragments;

import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.adapters.GoodsAdapter;
import com.xunshangwang.pinhaohuo.decorations.GoodsItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Goods;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.ui.activities.GoodsDetailActivity;
import com.xunshangwang.pinhaohuo.widgets.LMSizeRecyclerView;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.adapter.BaseRecyclerAdapter;
import tool.library.widget.LoadRecyclerView;

/**
 * Created by xzp on 16/1/25.
 */
public class MyGoodsFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,LoadRecyclerView.OnLoadListener,
        BaseRecyclerAdapter.OnItemClickListener{
    private LMSizeRecyclerView mRecycler;
    private RefreshLayout mRefresh;
    private GoodsAdapter mAdapter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_my_collection,container,false);
        mRefresh = (RefreshLayout) view.findViewById(R.id.refresh_layout);
        mRecycler = (LMSizeRecyclerView) view.findViewById(R.id.my_collection_list);
        mRecycler.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
        mRecycler.addItemDecoration(new GoodsItemDecoration(inflater.getContext()){
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position=parent.getChildAdapterPosition(view);
                if(position!=mAdapter.getItemCount()-1)
                    super.getItemOffsets(outRect, view, parent, state);
            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAdapter=new GoodsAdapter(getContext());
        mRecycler.setAdapter(mAdapter);
        mRecycler.setOnLoadListener(this);
        mAdapter.setOnItemClickListener(this);
        mRefresh.setOnRefreshListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        },150);
    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
//        Intent intent=new Intent(getContext(), GoodsDetailActivity.class);
//        intent.putExtra("id",mAdapter.getList().get(position).getGoods_id());
//        startActivity(intent);
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("pin://www.xunshangwang.com/goods/detail?id=" + mAdapter.getList().get(position).getGoods_id()));
        startActivity(intent);
    }

    @Override
    public void onLoad(LoadRecyclerView recyclerView) {
        LoadCollections();
    }

    @Override
    public void onRefresh() {
        refreshCollections();
    }

    private void refreshCollections(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Favorites&a=lists");
        builder.append("&fav_type=1");
        builder.append("&offset=0");
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        builder.append("&token="+getMainApplication().getToken());
        JsonHttpHandler<List<Goods>> handler=new JsonHttpHandler<List<Goods>>() {
            @Override
            public List<Goods> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("favoritesLists"),Goods.class);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Goods> response) {
                mAdapter.setList(response);
                mRecycler.loadFinish(response);
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(), builder.toString(), handler);
    }
    private void LoadCollections(){
        StringBuilder builder=new StringBuilder();
        builder.append("&fav_type=1");
        builder.append("&offset="+mAdapter.getListSize());
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        builder.append("&token="+getMainApplication().getToken());
        JsonHttpHandler<List<Goods>> handler=new JsonHttpHandler<List<Goods>>() {
            @Override
            public List<Goods> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("favoritesLists"),Goods.class);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mRecycler.loadFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Goods> response) {
                mAdapter.addAll(response);
                mRecycler.loadFinish(response);
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(), builder.toString(), handler);
    }
}
